import mysql.connector
from mysql.connector import Error

from mysql_config import *

try:
    # 建立连接
    print('正在连接数据库...')
    connection = mysql.connector.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        database=database
    )
    print('成功连接数据库')

    if connection.is_connected():
        db_Info = connection.get_server_info()
        print(f"Connected to MySQL Server version {db_Info}")

        # 创建游标对象
        cursor = connection.cursor()

        # 执行 SQL 查询
        cursor.execute(f"SELECT * FROM {table}")
        records = cursor.fetchall()
        print("Total number of rows in table: ", cursor.rowcount)

        print("\nPrinting each row")
        for row in records:
            print(row)

except Error as e:
    print(f"Error while connecting to MySQL: {e}")

finally:
    # 关闭游标和连接
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")